package com.demo.api.conf;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: cja
 * @date: 2019/11/13 20:25
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Pointcut("execution(* com.demo.api.controller.*Controller.*(..))")
    public void logAspect(){
    }

    @Around("logAspect()")
    public Object doAroud(ProceedingJoinPoint point) throws Throwable{
        RequestAttributes atts = RequestContextHolder.getRequestAttributes();
        if(atts == null){
            return point.proceed();
        }
        ServletRequestAttributes srAtts = (ServletRequestAttributes) atts;
        HttpServletRequest request = srAtts.getRequest();
        String uri = request.getRequestURI();
        Object[] args = point.getArgs();
        try{
            //过滤请求数据
            List<Object> paramsArgs = Arrays.asList(args).stream().filter(
              arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse))
            ).collect(Collectors.toList());
            String params = "";
            if(args.length > 0){
                //key-value参数
                Enumeration em = request.getParameterNames();
                while (em.hasMoreElements()){
                    String name = String.valueOf(em.nextElement());
                    String value = request.getParameter(name);
                    params += name + "=" + value + "&";
                }
            }
            //json参数
            if(paramsArgs.size() >= 1 && params.length() == 0){
                params += JSON.toJSONString(paramsArgs.get(0));
            }
            log.info("请求接口：{},请求数据:{}",uri, StringUtils.isEmpty(params) ? "无" : params);
            Object obj = point.proceed();
            log.info("请求接口：{},响应数据:{}",uri,JSON.toJSONString(obj));
            return obj;
        }catch (Exception e){
            if(e instanceof BussException){
                BussException be = (BussException) e;
                throw be;
            } else {
                throw new Throwable(e);
            }
        }
    }
}
